﻿var _ = require('underscore');

var DatabaseSchemaReader = require('happy.database.schem.reader').DatabaseSchemaReader;
var CodeGenerator = require('happy.code.generator').CodeGenerator;

module.exports.generate = function (project) {
    var schemaReader = DatabaseSchemaReader.createSqlClientReader(project.connectionString);

    schemaReader.readAll(function (error, schema) {
        if (error) {
            console.log(error)
            return;
        }

        var tables = project.tables;

        _.each(schema.tables, function (table) {
            if (tables[table.name]) {
                _.extend(tables[table.name], table);
            }
        });

        var aggregates = _.filter(_.values(tables), function (table) { return table.isAggregate === true });

        _.each(aggregates, function (aggregate) {
            aggregate.entities = _.filter(_.values(tables), function (table) {
                return table.isEntity === true && table.aggregate === aggregate.name;
            });
        });

        //生成服务器端代码
        _.each(aggregates, function (aggregate) {
            CodeGenerator.executeTemplateDirectory('./templates/Server/Aggregate', _.extend({
                aggregate: aggregate
            }, project));
            _.each(aggregate.entities, function (entity) {
                CodeGenerator.executeTemplateDirectory('./templates/Server/Entity', _.extend({
                    aggregate: aggregate,
                    entity: entity
                }, project));
            });
        });
        CodeGenerator.executeTemplateDirectory('./templates/Server/Project', _.extend({
            aggregates: aggregates
        }, project));

        //生成客户端代码
        if (project.client !== false) {
            _.each(tables, function (table) {
                CodeGenerator.executeTemplateDirectory('./templates/Client', _.extend({
                    table: table
                }, project));
            });
        }

        console.log('success!')
    });
};
